<template>
  <h1>{{ msg }}</h1>

  <div class="card">
    <button type="button" @click="count++">count is {{ count }}</button>
    <button type="button" @click="sendMsg">data-发送消息给基座</button>
    <button type="button" @click="sendGlogalMsg">全局消息-发送消息给基座</button>
    <p>
      Edit
      <code>components/HelloWorld.vue</code> to test HMR
    </p>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { EventCenterForMicroApp } from '@micro-zoe/micro-app';
defineProps<{ msg: string }>()
const count = ref(0)

// 创建事件中心实例
const eventCenter = new EventCenterForMicroApp('child-app');

const sendGlogalMsg = () => {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    console.log('sendGlogalMsg')
    // 使用官方推荐的数据通信方式
    // 向基座应用发送数据
    window.microApp.setGlobalData({
      type: 'globalchild-msg',  // 事件类型
      data: {
        msg: 'global-这是子应用发送的消息',
        from: 'global-vue-child'
      }
    })
    console.log('[Vue子应用] 全局消息已发送')
  } else {
    console.log('[Vue子应用] 非微前端环境')
  }
}

// 修改发送消息的方法
const sendMsg = () => {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    // 确保使用正确的事件中心对象
    const eventCenter = (window as any).eventCenterForChildApp
    if (eventCenter) {
      eventCenter.dispatch({
        type: 'child-msg',
        data: {
          msg: '来自子应用的消息',
          timestamp: Date.now()
        }
      })
      console.log('[Vue子应用] 消息已发送')
    } else {
      console.error('[Vue子应用] 事件中心未初始化')
    }
  }
}

onMounted(() => {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    
    // 直接使用固定的应用名称，确保与注册名称一致
    const appName = 'child-app'  // 使用固定名称而不是从 window.__MICRO_APP_NAME__ 获取
    console.log('[Vue子应用][onMounted] 当前应用名称:', appName);
    
    window.microApp.addDataListener(appName, (data: any) => {
      console.log('[Vue子应用] ====== 收到数据 ======')
      console.log('[Vue子应用] 数据类型:', data?.type)
      console.log('[Vue子应用] 数据内容:', data?.data)
      console.log('[Vue子应用] 原始数据:', data)
      console.log('[Vue子应用] ====== 数据结束 ======')
    })
    console.log('[Vue子应用] 数据监听器已添加')
  }
})

onUnmounted(() => {
  if (window.__MICRO_APP_ENVIRONMENT__) {
    const appName = (window as any).__MICRO_APP_NAME__
    window.microApp.clearDataListener(appName)
  }
})
</script>
<style scoped>
.read-the-docs {
  color: #888;
}
</style>
